package com.yb.login.center.strategy.user;

import com.yb.auth.core.bean.SysUser;
import com.yb.auth.core.bean.SysUserPassAuthentication;
import com.yb.auth.core.constant.LoginConstant;
import com.yb.core.constant.HttpConstant;
import com.yb.core.exception.YbBusinessException;
import com.yb.core.util.JwtTokenUtil;
import com.yb.core.util.RedisUtil;
import com.yb.login.center.template.AbstractUserServiceTemplate;
import com.yb.login.center.util.LoginSecure;
import com.yb.login.center.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/11/12 22:23
 * FileName: LoginServiceImpl
 * Description:
 */

@Service
@Slf4j
public class UserPassLoginStrategy extends AbstractUserServiceTemplate {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    LoginSecure loginSecure;

    @Override
    public Authentication loadAuthentication(LoginVo loginVo) {
        String username = loginVo.getUsername();

        if(Objects.isNull(username)){
            throw new YbBusinessException(HttpConstant.Response.USER_EMPTY);
        }
        String password = loginVo.getPassword();

        if(Objects.isNull(password)){
            throw new YbBusinessException(HttpConstant.Response.PASS_EMPTY);
        }

        if(!StringUtils.hasText(loginVo.getImgUUID())){
            throw new YbBusinessException();
        }

        String verifyCode = loginVo.getVerifyCode();

        if(!StringUtils.hasText(verifyCode)){
            throw new YbBusinessException(HttpConstant.Response.VERIFY_CODE_EMPTY);
        }

        SysUserPassAuthentication authenticationToken = new SysUserPassAuthentication(username, password);
        authenticationToken.setVerifyCode(verifyCode);
        authenticationToken.setImgUUID(loginVo.getImgUUID());
        return authenticationToken;
    }

    @Override
    public SysUser loadSysUser(Authentication authentication) {
        if(authentication instanceof SysUserPassAuthentication){
            SysUserPassAuthentication sysUserPassAuthentication = (SysUserPassAuthentication) authentication;
            return sysUserPassAuthentication.getSysUser();
        }
        return null;
    }

    @Override
    protected LoginConstant.LoginType getLoginType() {
        return LoginConstant.LoginType.USER_PASS;
    }


}
